<script setup>
import { ArrowLeftBold, ArrowRight, CircleCloseFilled, Search } from '@element-plus/icons-vue'
import { getDeptTree } from '@/assets/api/dept'
import { ElMessage } from 'element-plus'
import useContacts from '@/store/contacts.js'
import useChannel from '@/store/channel.js'
import { getChannelMembers } from '@/assets/api/dialog-group.js'
import useUser from '@/store/user.js'
import { getUserInfoByUserId } from '@/assets/api/user.js'

const MAX_SELECT_COUNT = 1000
const props = defineProps({
  modelValue: Boolean,
  // 默认选中的人员
  defaultCheckedList: {
    type: Array,
    default: () => [],
  },
  disabledMethod: Function,
})
const { defaultCheckedList } = toRefs(props)
const emit = defineEmits(['update:modelValue', 'submit'])

const channelStore = useChannel()
const contactsStore = useContacts()
const userStore = useUser()
let flatDept = new Map()
const treeHeight = ref(0)
const searchValue = ref('')
const userListRef = ref()
const treeRef = ref()

const loading = ref(false)
const memberLoading = ref(false)

const groupName = ref('')
const tabActive = ref('')
const tabVisible = ref(true)
const membersList = ref([])
const groupMemberVisible = ref(false)
// 当前机会标签
const currentTag = ref(1)

watch(searchValue, (v) => {
  treeRef.value.filter(v)
})

// 选中的人员
const selectList = ref([])

// 选中人员id
const selectIdsList = ref([])

const userData = ref([])

const userInfo = ref({})

watch(
  () => props.modelValue,
  (v) => {
    if (v) {
      getUserListData()
      nextTick(() => {
        treeHeight.value = userListRef.value.getBoundingClientRect().height || 380
      })
    } else {
      close()
      setTimeout(() => {
        submitLoading.value = false
      }, 1000)
    }
  }
)

const searchTag = ref([
  { label: '单聊', value: 1 },
  { label: '群聊', value: 5 },
  { label: '组织架构', value: 0 },
])

function getUserInfoData(userId) {
  loading.value = true
  getUserInfoByUserId(userId).then((res) => {
    if (res.code === 200) {
      userInfo.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    nextTick(() => {
      loading.value = false
    })
  })
}

const filterChannelList = computed(() =>
  channelStore.channelList.filter((i) => i.name.includes(searchValue.value) && i.type === currentTag.value)
)
const filterMembersList = computed(() =>
  filterChannelList.value?.map((i) => {
    const data =
      i.type === 5
        ? i
        : {
            avatar: i.icon,
            label: i.name,
            nickName: i.realName || i.name,
            id: i.ext.userId,
            isUser: true,
            userId: i.ext.userId,
            checked: defaultCheckedList.value?.some((i) => i.id === i.ext?.userId),
            // disabled: props.disabledMethod ? props.disabledMethod(i) : false,
            disabled: false,
            channelId: i.id,
            type: i.type,
          }
    if (i.type !== 5) data.disabled = props.disabledMethod ? props.disabledMethod(data) : false
    return data
  })
)

const singleChatList = computed(() =>
  channelStore.channelList
    ?.filter((item) => item.type === 1)
    .map((i) => {
      return {
        avatar: i.icon,
        label: i.name,
        nickName: i.realName || i.name,
        id: i.ext.userId,
        userId: i.ext.userId,
        isUser: true,
        checked: false,
        disabled: i.ext.userId === userStore.userId,
        channelId: i.id,
        type: i.type,
      }
    })
)

function handleTabChange(value) {
  tabActive.value = value
  currentTag.value = value === 'groupChat' ? 5 : 0
  tabVisible.value = false
}

function goBack() {
  if (groupMemberVisible.value) {
    currentTag.value = 5
    tabVisible.value = false
    groupMemberVisible.value = false
    tabActive.value = 'groupChat'
  } else {
    currentTag.value = 1
    tabVisible.value = true
    tabActive.value = ''
  }
}

function sortUser(dept) {
  if (dept.children !== null && dept.children.length > 1) {
    dept.children.sort((v1, v2) => {
      if (v1.isDept && v2.isDept) {
        return 0
      } else if (v1.isDept && v2.isUser) {
        return 1
      } else if (v1.isUser && v2.isDept) {
        return -1
      } else {
        return (v1.seq || 1) - (v2.seq || 1)
      }
    })
    dept.children.forEach((cdept) => {
      if (cdept.isDept) {
        sortUser(cdept)
      }
    })
  }
}

function getUserListData() {
  loading.value = true
  Promise.all([getDeptTree()]).then((res) => {
    const userListData = JSON.parse(JSON.stringify(contactsStore.contactsData))
    const deptTree = JSON.parse(JSON.stringify(contactsStore.deptTree))
    flatDepts(deptTree)
    // 无部门的人
    const noDeptUserList = []
    userListData.forEach((user) => {
      const { deptIds } = user
      user.label = user.nickName
      user.id = user.userId
      user.isUser = true
      user.checked = defaultCheckedList.value.some((i) => i.id === user.id)
      // if (user.checked) {
      //   selectList.value.push(user)
      // }
      if (props.disabledMethod) {
        user.disabled = props.disabledMethod(user)
      }
      if (deptIds && deptIds.length) {
        deptIds.forEach((deptId) => {
          const target = flatDept.get(deptId)
          if (target) {
            target.children.push(user)
          }
        })
      } else {
        noDeptUserList.push(user)
      }
    })
    userData.value = deptTree.concat(noDeptUserList)

    deptTree.forEach((deptItem) => {
      sortUser(deptItem)
    })

    loading.value = false
    // const deptTreeData = res[1].data
    // // 无部门的人
    // const userList = []
    // userListData.forEach((user) => {
    //   const { deptIds } = user
    //   user.label = user.nickName
    //   user.id = user.userId
    //   user.isUser = true
    //   user.checked = false
    //   if (props.disabledMethod) {
    //     user.disabled = props.disabledMethod(user)
    //   }
    //   if (deptIds) {
    //     deptIds.forEach((deptId) => {
    //       const target = findDept(deptTreeData, deptId)
    //       if (!target.children) {
    //         target.children = []
    //       }
    //       target.children.push(user)
    //     })
    //   } else {
    //     userList.push(user)
    //   }
    //   if (defaultCheckedList.value.some((i) => i.id === user.id)) {
    //     user.checked = true
    //     selectList.value.push(user)
    //   }
    // })
    // userData.value = deptTreeData.concat(userList)
    // // setCheckedNodes()
    // loading.value = false
  })
}

function flatDepts(depts) {
  return depts.concat(
    depts
      .map((i) => {
        if (!i.children) {
          i.children = []
        }
        i.disabled = false
        i.checked = false
        i.isDept = true
        i.indeterminate = false
        flatDept.set(i.id, i)
        return flatDepts(i.children)
      })
      .flat()
  )
}

function filterUser(value, node) {
  if (!value || node.label.includes(value)) {
    return true
  }
  if (!node.isDept) {
    if (node.depts) {
      return node.depts.some((i) => i.deptName.includes(value))
    } else {
      return node.label.includes(value)
    }
  }
  return false
}

function checked(node, value) {
  if (selectList.value.length < MAX_SELECT_COUNT || !value) {
    node.data.checked = value === undefined ? !node.data.checked : value
    if (node.data.isDept && node.children) {
      node.children.forEach((i) => {
        if (!i.data.disabled) {
          checked(i, node.data.checked)
        }
      })
    } else if (node.data.isUser) {
      if (node.data.checked && selectList.value.every((i) => i.id !== node.data.id)) {
        selectList.value.push(node.data)
        selectIdsList.value.push(node.data.id)
      }
      if (!node.data.checked) {
        const index = selectList.value.findIndex((i) => i.id === node.data.id)
        selectList.value.splice(index, 1)
        selectIdsList.value.splice(index, 1)
      }
    }
    if (node.parent) {
      if (node.parent.children.every((i) => i.data.checked)) {
        node.parent.data.checked = true
        node.parent.data.indeterminate = false
      } else if (node.parent.children.every((i) => !i.data.checked)) {
        node.parent.data.checked = false
        node.parent.data.indeterminate = false
      } else {
        node.parent.data.indeterminate = true
      }
    }
  }
}

function handleChangeCheckbox(value, data) {
  getUserInfoData(data.userId)
  data.extUserName = userInfo.value.extUserName
  const checked = selectIdsList.value.includes(data.id)
  // const filtered = singleChatList.value.concat(membersList.value)
  // const uniqueArr = filtered.filter((item, index) => {
  //   return filtered.findIndex(i => i.id === item.id) === index
  // })
  // const userList = uniqueArr.filter(i => {
  //   i.checked = checked
  //   return value.includes(i.id)
  // })
  // selectGroupList.value = userList
  if (checked) {
    data.checked = checked
    // selectList.value.push(...userList)
    selectList.value.push(data)
  } else {
    selectList.value = selectList.value.filter((i) => i.id !== data.id)
  }
}

function deselect(data) {
  checked(treeRef.value.getNode(data), false)
}

// 查看群聊下的成员
function handleClickMembers(data) {
  groupMemberVisible.value = true
  memberLoading.value = true
  groupName.value = data.name
  getChannelMembers(data.id).then((res) => {
    if (res.code === 200) {
      membersList.value = res.rows.map((item) => {
        const data = {
          avatar: item.avatar,
          label: item.realName || item.name,
          nickName: item.realName || item.name,
          id: item.userId,
          userId: item.userId,
          channelId: item.id,
          isUser: true,
          // checked: false,
          // disabled: item.userId === userStore.userId,
          checked: defaultCheckedList.value.some((i) => i.id === item.userId),
          disabled: false,
        }

        data.disabled = props.disabledMethod ? props.disabledMethod(data) : false
        return data
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
  memberLoading.value = false
}

const submitLoading = ref(false)

function submit() {
  if (selectList.value.length !== 0) {
    submitLoading.value = true
    emit('submit', JSON.parse(JSON.stringify(selectList.value)))
  } else {
    ElMessage.warning('请选择人员')
  }
}

function open() {
  // console.log('defaultCheckedList', defaultCheckedList.value)
  // // // selectList.value = Array.from(new Set(defaultCheckedList.value.map(i => i.id))).map(id => defaultCheckedList.value.find(item => item.id === id))
  // selectList.value = defaultCheckedList.value
  // selectIdsList.value = defaultCheckedList.value.map(i => i.id)
  // // console.log('selectList.value', selectList.value)
}

function close() {
  searchValue.value = ''
  selectList.value = []
  selectIdsList.value = []
  userData.value = []
  membersList.value = []
  tabVisible.value = true
  tabActive.value = ''
  groupName.value = ''
  groupMemberVisible.value = false
  currentTag.value = 1
  emit('update:modelValue', false)
}
</script>

<template>
  <TaskChatDialog
    :model-value="props.modelValue"
    class="personnel-selection"
    title="人员选择"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    @open="open"
    @close="close">
    <!--<el-input v-model="searchValue" :prefix-icon="Search" clearable></el-input>-->
    <div class="personnel-selection-body">
      <div class="perosonal-user-body">
        <el-input v-model="searchValue" :prefix-icon="Search" clearable></el-input>
        <div class="tab-change" v-show="tabVisible">
          <div class="tab-change-item" @click="handleTabChange('groupChat')">
            <div class="item-svg-icon">
              <SvgIcon icon-name="create-group3" size="30"></SvgIcon>
            </div>
            <span>群聊</span>
          </div>
          <div class="tab-change-item" @click="handleTabChange('organization')">
            <div class="item-svg-icon">
              <SvgIcon icon-name="im-arch-setting" size="30"></SvgIcon>
            </div>
            <span>组织架构</span>
          </div>
        </div>

        <div class="tab-back" v-show="!tabVisible">
          <el-icon size="16" color="" @click="goBack">
            <ArrowLeftBold />
          </el-icon>
          <div class="tab-back-text" v-if="!groupMemberVisible">
            {{ tabActive === 'organization' ? '按组织架构选' : '按群聊选' }}
          </div>
          <div class="tab-back-text" v-else>{{ groupName }}</div>
        </div>
        <div v-loading="loading" ref="userListRef" class="user-list" v-show="tabActive === 'organization'">
          <div class="tab-title">组织架构</div>
          <div class="tab-content">
            <el-tree-v2
              ref="treeRef"
              :height="treeHeight"
              :data="userData"
              :icon="ArrowRight"
              :filter-method="filterUser">
              <template #default="{ node, data }">
                <div>
                  <el-checkbox
                    :model-value="data.isDept ? data.checked : selectList.some((i) => i.id === data.id)"
                    :indeterminate="data.indeterminate"
                    :disabled="data.disabled"
                    style="margin-right: 5px"
                    @click.stop
                    @change="checked(node, $event)"></el-checkbox>
                  <span>{{ node.label }}</span>
                </div>
              </template>
            </el-tree-v2>
          </div>
        </div>
        <div v-show="tabActive !== 'organization'">
          <div class="user-personal-list group-checked-container" v-show="!groupMemberVisible">
            <div class="user-list-checkbox" v-if="currentTag === 1">
              <div class="user-item" v-for="item in filterMembersList" :key="item.id">
                <el-checkbox-group v-model="selectIdsList" @change="(value) => handleChangeCheckbox(value, item)">
                  <el-checkbox :value="item.id" :label="item.label" :disabled="item.disabled">
                    <template #default>
                      <div class="group-text">
                        <el-avatar :src="item.avatar" :size="34">
                          <SvgIcon
                            :icon-name="`dialog-default-img-${item.channelId.slice(-6, -2) % 4}`"
                            circle
                            size="34" />
                        </el-avatar>
                        <div class="group-name text-overflow-ellipsis">{{ item.label }}</div>
                      </div>
                    </template>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <div class="group-list" v-else>
              <div class="group-item" v-for="item in filterMembersList" :key="item.id">
                <div class="group-text">
                  <el-avatar :src="item.avatar" :size="34">
                    <SvgIcon :icon-name="`dialog-default-img-${item.id.slice(-6, -2) % 4}`" circle size="34" />
                  </el-avatar>
                  <div class="group-name text-overflow-ellipsis">{{ item.name }}</div>
                </div>
                <div class="group-btn" v-if="item.type === 5" @click="() => handleClickMembers(item)">成员</div>
              </div>
            </div>
            <!--<el-checkbox-group v-model="selectList">-->
            <!--  <el-checkbox v-for="item in selectList" :label="item.label" :value="item.id"></el-checkbox>-->
            <!--</el-checkbox-group>-->
          </div>
          <div v-if="groupMemberVisible" class="group-checked-container" v-loading="memberLoading">
            <div class="user-list-checkbox">
              <div class="user-item" v-for="item in membersList" :key="item.id">
                <el-checkbox-group v-model="selectIdsList" @change="(value) => handleChangeCheckbox(value, item)">
                  <el-checkbox :value="item.id" :label="item.label" :disabled="item.disabled">
                    <template #default>
                      <div class="group-text">
                        <el-avatar :src="item.avatar" :size="34">
                          <SvgIcon
                            :icon-name="`dialog-default-img-${item.channelId.slice(-6, -2) % 4}`"
                            circle
                            size="34" />
                        </el-avatar>
                        <div class="group-name text-overflow-ellipsis">{{ item.label }}</div>
                      </div>
                    </template>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="selected-user-list">
        <div style="font-weight: bold; font-size: 16px">
          已选择
          {{ selectList.length }} / {{ MAX_SELECT_COUNT }} 人
        </div>
        <div class="user" v-for="item in selectList" :key="item.id">
          <span>{{ item.label }}</span>
          <el-icon v-if="!item.disabled" size="16" @click="deselect(item.id)" style="cursor: pointer">
            <CircleCloseFilled></CircleCloseFilled>
          </el-icon>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" @click="submit" :loading="submitLoading" :disabled="!selectList.length">确认</el-button>
    </template>
  </TaskChatDialog>
</template>

<style lang="scss">
.el-dialog.fiz-eim-dialog.personnel-selection {
  .fiz-eim-dialog-body {
    padding: 10px 0;
  }

  .el-dialog__body {
    overflow: hidden;
  }
}
</style>
<style scoped lang="scss">
.personnel-selection {
  .personnel-selection-body {
    @include use-flex();
    //height: 500px;
    .user-list {
      flex: 1;
      padding: 0 10px;
      //border-right: var(--elp-border);
      //overflow: hidden auto;
      .organization-img {
        width: 10px;
        height: 10px;
      }
    }

    .perosonal-user-body {
      width: 50%;
      flex: 1;
      padding: 0 10px;
      border-right: var(--elp-border);

      .tab-change {
        @include use-flex(center);
        margin: 20px 0;

        .tab-change-item {
          margin-right: 50px;
          cursor: pointer;
          text-align: center;

          .item-svg-icon {
            @include use-flex(center, center);
            width: 46px;
            height: 46px;
            background-color: rgba(102, 102, 102, 0.1);
            border-radius: 6px;
            margin-bottom: 6px;
          }

          & > span {
            font-size: 14px;
            color: #333;
          }
        }
      }

      .tab-back {
        //width: 100%;
        @include use-flex(center, center);
        padding: 20px 0;

        .el-icon {
          position: absolute;
          left: 20px;
          cursor: pointer;
        }

        .tab-back-text {
        }
      }

      .user-list {
        height: calc(100% - 56px);
        //overflow: hidden auto;
        .tab-title {
          margin-bottom: 10px;
          font-size: 16px;
          color: #999;
        }

        .tab-content {
          height: calc(100% - 30px);
        }

        .organization-img {
          width: 10px;
          height: 10px;
        }
      }
    }

    .user-personal-list {
      height: 370px;
      overflow-y: auto;

      .group-list {
        .group-item {
          @include use-flex(center, space-between);
          width: 100%;
          height: 48px;

          .group-text {
            width: calc(100% - 50px);
            @include use-flex(center);

            .group-name {
              margin: 0 15px;
              width: calc(100% - 70px);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .group-btn {
            width: 50px;
            float: right;
            padding: 0 10px;
            border-left: 1px solid #bdb5b5;
            cursor: pointer;
          }
        }
      }
    }

    .group-checked-container {
      height: 415px;

      .el-checkbox-group {
        @include use-flex(flex-start, center);
        flex-direction: column;

        .el-checkbox {
          margin-bottom: 10px;
        }

        .el-checkbox__label {
          .group-text {
            @include use-flex(center);

            .group-name {
              padding-left: 10px;
            }
          }
        }
      }
    }

    .selected-user-list {
      flex: 1;
      width: 50%;
      padding: 0 10px;
      overflow-y: auto;

      .user {
        display: inline-flex;
        align-items: center;
        font-size: 12px;
        color: #0d53ff;
        border-radius: 4px;
        padding: 4px 8px;
        border: 1px solid #0d53ff;
        margin-right: 10px;
        margin-top: 5px;
        background: rgba(13, 83, 255, 0.1);
      }
    }
  }
}
</style>
